package org.hbgl.geoentity.admin.web;

import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.hbgl.geoentity.admin.shiro.LoginUser;
import org.hbgl.geoentity.core.storage.StorageService;
import org.hbgl.geoentity.core.util.Base64AndImage;
import org.hbgl.geoentity.core.util.ResponseUtil;
import org.hbgl.geoentity.db.domain.*;
import org.hbgl.geoentity.db.service.*;
import org.hbgl.geoentity.db.util.JsonUtil;
import org.hbgl.geoentity.db.vo.BusinessLicense;
import org.hbgl.geoentity.db.vo.BusinessLicenseOCR;
import org.hbgl.geoentity.db.vo.ResponseObject;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * 代码功能：
 * 开发日期：2022/5/10
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
public class BaseController {

    @Resource
    public DicService dicService;
    @Resource
    public GePermissionService permissionService;
    @Resource
    public GeRoleService roleService;
    @Resource
    public GeStorageService geStorageService;
    @Resource
    public GeSystemparameterService systemparameterService;
    @Resource
    public GeUnitService unitService;
    @Resource
    public GeUserService userService;
    @Resource
    public LogService logService;
    @Resource
    public NodeService nodeService;

    @Resource
    public HttpServletRequest request;
    @Resource
    private Producer kaptchaProducer;
    @Resource
    public StorageService storageService;

    @Resource
    public GeDepartmentService departmentService;
    @Resource
    public GeColumnService columnService;
    @Resource
    public GeContentService contentService;
    @Resource
    public VerifyService verifyService;

    public static List<DicAddress> addressAll = new ArrayList<>();
    public static List<DicUnitType> unitTypeAll = new ArrayList<>();
    public static List<DicTrade> tradeAll = new ArrayList<>();

    public String doKaptcha() {
        HttpSession session=null;
        // 生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
         session =request.getSession();
        session.setAttribute("kaptcha", text);
        System.out.println("kaptcha===>"+text+",id===>"+session.getId());
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
        } catch (IOException e) {
            return null;
        }
    }
    public String getkaptcha(){
        HttpSession session =request.getSession();
        String kaptcha = (String) session.getAttribute("kaptcha");
        System.out.println("kaptcha2===>"+kaptcha+",id===>"+session.getId());
        return  kaptcha;
    }
    public GeUser getCurrentAdminUser() {
        Subject subject = SecurityUtils.getSubject();
        LoginUser userCurrent = (LoginUser) subject.getPrincipal();
        if (userCurrent == null || userCurrent.getAdminUser() == null) {
            throw new AuthenticationException();
        }
        return userCurrent.getAdminUser();
    }

    public GeUser getCurrentUnitUser() {
        Subject subject = SecurityUtils.getSubject();
        LoginUser userCurrent = (LoginUser) subject.getPrincipal();
        if (userCurrent == null || userCurrent.getUnitUser() == null) {
            throw new AuthenticationException();
        }
        return userCurrent.getUnitUser();
    }


    /**
     * 验证企业信息真实性
     *
     * @param organUnit 企业信息
     * @return
     */
    public Object verifyUnitinfoAuthenticity(GeUnit organUnit) {
        try {
            ResponseObject responseObject = new ResponseObject();

            //region 企业三要素核验
            responseObject = verifyService.verifyFactor3Precise(organUnit.getUnitName(), organUnit.getUnitCode(), organUnit.getCorporation());
            if (responseObject.getCode() != 200) {
                return ResponseUtil.fail(-1, "企业三要素核验不通过：" + responseObject.getMsg());
            }
            if (responseObject.getData() == null || responseObject.getData().getResult() == null) {
                return ResponseUtil.fail(-1, "企业三要素核验不通过：结果异常");
            }
            if (!"1".equals(responseObject.getData().getResult().toString())) {
                System.out.println("公司名称：" + organUnit.getUnitName());
                System.out.println("统一社会信用代码：" + organUnit.getUnitCode());
                System.out.println("法人姓名：" + organUnit.getCorporation());

                return ResponseUtil.fail(-1, "企业三要素核验不通过：单位名称、统一社会信用代码、法定代表人姓名不匹配");
            }
            //endregion

            //region 实名认证
            if (StringUtils.isNotBlank(organUnit.getCorporation()) && StringUtils.isNotBlank(organUnit.getCredentials())) {
                responseObject = verifyService.verifyIdcardName(organUnit.getCorporation(), organUnit.getCredentials());
                if (responseObject.getCode() != 200) {
                    return ResponseUtil.fail(-1, "实名认证不通过：" + responseObject.getMsg());
                }
                if (responseObject.getData() == null || responseObject.getData().getResult() == null) {
                    return ResponseUtil.fail(-1, "实名认证不通过：结果异常");
                }
                if (!"1".equals(responseObject.getData().getResult().toString())) {
                    System.out.println("法定代表人姓名：" + organUnit.getCorporation());
                    System.out.println("法定代表人证件号：" + organUnit.getCredentials());

                    return ResponseUtil.fail(-1, "实名认证不通过：法定代表人姓名、法定代表人证件号不匹配");
                }
            }
            //endregion

            //region 营业执照验真
            if(StringUtils.isNotBlank(organUnit.getLicense())) {
                //region 营业执照OCR
//                String uploadDir = UPLOADURL + "/UploadImages/";
//                String marginImageFile = uploadDir + organUnit.getOrganunitlicense();
//                BufferedImage image = ImageIO.read(Files.newInputStream(Paths.get(marginImageFile)));

                URL urlfile = new URL(organUnit.getLicense());
                InputStream inStream = urlfile.openStream();
                BufferedImage image= ImageIO.read(inStream);

                String imageBase64 = Base64AndImage.imageToBase64String(image);
                responseObject = verifyService.verifyBusinessLicenseOcr(imageBase64);
                if (responseObject.getCode() != 200) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：" + responseObject.getMsg());
                }
                if (responseObject.getData() == null || responseObject.getData().getResult() == null) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：结果异常");
                }
                Object result = responseObject.getData().getResult();
                String serialize = JsonUtil.serialize(result);
                BusinessLicenseOCR businessLicenseOCR = JsonUtil.deserialize(serialize, BusinessLicenseOCR.class);
//                BusinessLicenseOCR businessLicenseOCR = (BusinessLicenseOCR) responseObject.getData().getResult();
                if (businessLicenseOCR == null) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：结果异常");
                }
                if (!StringUtils.equals(organUnit.getUnitName(), businessLicenseOCR.getName())) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：企业名称与营业执照不匹配");
                }
                //endregion
                //region 营业执照验真
                responseObject = verifyService.verifyBusinessLicense(organUnit.getUnitName());
                if (responseObject.getCode() != 200) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：" + responseObject.getMsg());
                }
                if (responseObject.getData() == null || responseObject.getData().getResult() == null) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：结果异常");
                }
                Object result1 = responseObject.getData().getResult();
                String serialize1 = JsonUtil.serialize(result1);
                BusinessLicense businessLicense = JsonUtil.deserialize(serialize1, BusinessLicense.class);
//                BusinessLicense businessLicense = (BusinessLicense) responseObject.getData().getResult();
                if (businessLicense == null) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：结果异常");
                }
                //endregion
                String errorNameStr = "";
                if (!Objects.equals(businessLicenseOCR.getName(), businessLicense.getName())) {
                    errorNameStr += "单位名称、";
                }
                if (!Objects.equals(businessLicenseOCR.getRegistrationNumber(), businessLicense.getCreditNo())) {
                    errorNameStr += "统一社会信用代码、";
                }
                if (!Objects.equals(businessLicenseOCR.getLegalRepresentative(), businessLicense.getOperName())) {
                    errorNameStr += "法定代表人姓名、";
                }
                if (StringUtils.isNotBlank(errorNameStr)) {
                    errorNameStr = errorNameStr.substring(0, errorNameStr.length() - 1);
                }
                if (StringUtils.isNotBlank(errorNameStr)) {
                    return ResponseUtil.fail(-1, "营业执照验真不通过：" + errorNameStr + "等不匹配");
                }
            }
            //endregion
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();
    }


}
